<?php
namespace app\shop\model;

use app\BaseModel;
use app\farm\model\Coupon;
use think\facade\Db;

class LuckConfig extends BaseModel
{
    //定义表名
    protected $name = 'lbfarm_v2_luck_config';



    protected $append = [


        'coupon_title'
    ];


    /**
     * @param $value
     * @param $data
     * @功能说明:
     * @author chenniang
     * @DataTime: 2022-07-21 18:03
     */
    public function getCouponTitleAttr($value,$data){

        if(isset($data['coupon_id'])){

            $coupon_model = new Coupon();

            $title = $coupon_model->where(['id'=>$data['coupon_id']])->value('title');

            return $title;

        }


    }

    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:04
     * @功能说明:添加
     */
    public function dataAdd($data){

        $data['create_time'] = time();

         if(isset($data['data'])){

             $arr = $data['data'];

             unset($data['data']);
         }

        $res = $this->insert($data);

        $id  = $this->getLastInsID();

        if(isset($arr)){

            $this->updateSome($id,$arr,$data['uniacid']);

        }
        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2022-07-15 14:24
     * @功能说明:添加奖品信息
     */
    public function updateSome($id,$data,$uniacid){

        $config_model = new LuckConfig();

        $arr = [];

//        $config_model->where(['luck_id'=>$id])->delete();
        if(!empty($data)){

            foreach ($data as $k=>$v){

                $v['uniacid'] = $uniacid;

                $v['luck_id'] = $id;

                if(empty($v['id'])){

                    $config_model->insert($v);

                    $arr[] = $v['id'];

                }else{

                    $config_model->dataUpdate(['id'=>$v['id']],$v);

                    $arr[] = $config_model->getLastInsID();

                }

                $config_model->save($v);


            }

        }

        $config_model->where(['luck_id'=>$id])->where('id','not in',$arr)->delete();

        return true;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:05
     * @功能说明:编辑
     */
    public function dataUpdate($dis,$data){

        if(isset($data['data'])){

            $arr = $data['data'];

            unset($data['data']);
        }

        $res = $this->where($dis)->update($data);

        if(isset($arr)){

            $this->updateSome($dis['id'],$arr,$data['uniacid']);

        }

        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:06
     * @功能说明:列表
     */
    public function dataList($dis,$page){

        $data = $this->where($dis)->order('top desc,id desc')->paginate($page)->toArray();

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:43
     * @功能说明:
     */
    public function dataInfo($dis){

        $data = $this->where($dis)->find();

        return !empty($data)?$data->toArray():[];

    }








}